// #include "PptpServer.h"

// PptpServer::PptpServer(QObject *parent)
//     : QObject{parent}
// {
//     server = new QTcpServer;
//     connect(server, &QTcpServer::newConnection, this, &PptpServer::newClientHandler);
//     server->listen(QHostAddress::AnyIPv4, PORT);
// }
// void PptpServer::newClientHandler()
// {
//     ServerThread *t = new ServerThread(server);
//     connect(t, &ServerThread::pptpDisconnect, [this](PptpSocket *pptpSocket)
//             {
//         qDebug() << "pptpDisconnect";
//         pptpSocketList.removeOne(pptpSocket); });
//     t->start();
//     //connect(pptpSocket, &PptpSocket::readCompletedSignal, this, [this](QByteArray readMessage)
//     //        {
//     //            PptpSocket *pptpSocket = qobject_cast<PptpSocket *>(sender());
//     //            PptpServerRoute pptpServerRoute;
//     //            QByteArray writeMessage = pptpServerRoute.dispatchRequest(readMessage);
//     //            pptpSocket->pptpWrite(writeMessage); });
//     //connect(pptpSocket, &PptpSocket::pptpDisconnect, this, [this]()
//     //        {
//     //            PptpSocket *pptpSocket = qobject_cast<PptpSocket *>(sender());
//     //            pptpSocket->deleteLater();
//     //            pptpSocketList.removeOne(pptpSocket); });
//     //pptpSocketList.append(pptpSocket);
// }

#include "PptpServer.h"
#include "PptpServerRoute.h"

PptpServer::PptpServer(QObject *parent)
    : QObject{parent}
{
    server = new QTcpServer(this);
    connect(server, &QTcpServer::newConnection, this, &PptpServer::newClientHandler);
    server->listen(QHostAddress::AnyIPv4, PORT); // 开始监听指定端口
}

void PptpServer::newClientHandler()
{
    QTcpSocket *tcpSocket = server->nextPendingConnection(); // 获取新的连接
    if (!tcpSocket)
        return;

    PptpSocket *pptpSocket = new PptpSocket(tcpSocket, this); // 创建 PptpSocket

    // 处理数据读取的信号
    connect(pptpSocket, &PptpSocket::readCompletedSignal, this, [this, pptpSocket](QByteArray readMessage)
            {
                PptpServerRoute pptpServerRoute;
                QByteArray writeMessage = pptpServerRoute.dispatchRequest(readMessage); // 处理消息
                pptpSocket->pptpWrite(writeMessage);                                    // 回复客户端
            });

    // 处理客户端断开连接的信号
    connect(pptpSocket, &PptpSocket::pptpDisconnect, this, [this, pptpSocket]()
            {
                pptpSocket->deleteLater();            // 当连接断开时删除 socket
                pptpSocketList.removeOne(pptpSocket); // 从列表中移除该 socket
            });

    pptpSocketList.append(pptpSocket); // 添加到 socket 列表
}
